<style lang="less">
@import '../styles/common.less';
@import 'vm-btable.less';
</style>

<template>
  <Row>
    <Row type="flex" justify="space-between" v-if="isRow">
      <div v-if="isSearch">
        <div class="db_inline" v-if="textInput" style="margin: 0 0 0 5px">
          {{ searchText }}
        </div>
        <Input v-if="textInput" v-model="searchTxt" :placeholder="placeholder" style="width: 150px;margin: 0 10px 0 0"
               clearable/>
        <slot name="search" class="margin-left-10"></slot>
        <span @click="searchFn" v-if="clearBtn" style=""><Button type="primary" style="margin-right: 4px;"><Icon
          type="search"></Icon>搜索</Button></span>
        <Button @click="restFn" type="ghost" v-if="clearBtn">
          <Icon type="refresh"></Icon>
          {{ cleanText }}
        </Button>
      </div>
      <div class="control" v-if="isControl">
        <Button @click="addFn" v-if="addBtn" type="info">
          <Icon type="plus"></Icon>
          <span>{{ addText }}</span>
        </Button>
        <Button type="info" @click="templateDownload" v-if="downTemplate">
          <Icon type="android-arrow-down"></Icon>
          <span>{{ templateText }}</span>
        </Button>
        <slot name="download"></slot>
        <div class="db_inline" style=" direction: initial ;margin: 0 0 0 -3px">
          <Upload
            :action=action
            :headers=header
            :multiple="true"
            style="float: left;margin:0 4px"
            :on-success="handleSuccess"
            :before-upload="handleBeforeUpload"
            :on-error="handleError"
            :show-upload-list="false"
            v-if="importBtn">
            <Button type="info">
              <Icon type="android-arrow-up"></Icon>
              <span>批量导入</span>
            </Button>
          </Upload>
        </div>
        <slot name="import"></slot>
        <Button type="info" @click="exportFn" v-if="exportBtn" style="margin: 0 0 0 -4px">
          <Icon type="android-arrow-down"></Icon>
          <span>批量导出</span>
        </Button>
        <Button type="warning" @click="batchDelect" v-if="batchDelBtn">
          <Icon type="ios-trash-outline"></Icon>
          <span>批量删除</span>
        </Button>
        <slot name="operation"></slot>
      </div>
    </Row>
    <Row class="margin-top-10">
      <Table :height='tableHeight' ref="table" :border="border"  :columns="showColumns" :data="dataShow"
             @on-selection-change="selectChange"></Table>
    </Row>
    <Row type="flex" justify="end" class="footer">
      <div class="margin-top-10">
        <span>总共 {{ searchparam.total }} 条记录 &nbsp;</span>
        <Page class="db_inline" :total="searchparam.total" :current="searchparam.current" :page-size="searchparam.size"
              @on-change="pageChange" show-elevator></Page>
      </div>
    </Row>
    <Modal v-model="modalDelete" title="警告" v-on:on-ok="deleteOk">
      <Icon type="minus-circled" style="color: red"></Icon>
      {{ deleteText }}
    </Modal>
  </Row>
</template>

<script>
import API from "@/api/api";
import Axios from 'axios';
import Cookies from 'js-cookie';

export default {
  name: 'VmTable',
  components: {},
  props: {
    placeholder: String,
    action: String,
    actionsuccess: String,
    type: String,
    isRow: {
      type: Boolean,
      default: true
    },
    textInput: {
      type: Boolean,
      default: true
    },
    isSearch: {
      type: Boolean,
      default: true
    },
    border: {
      type: Boolean,
      default: false
    },
    cleanText: {
      type: String,
      default: '清空'
    },
    searchText: {
      type: String,
      default: '关键字：'
    },
    templateText: {
      type: String,
      default: '批量导入模板下载'
    },
    deleteText: {
      type: String,
      default: '您确定要删除该数据?'
    },
    addText: {
      type: String,
      default: '添加'
    },
    clearBtn: {
      type: Boolean,
      default: true
    },
    isControl: {
      type: Boolean,
      default: true
    },
    importBtn: {
      type: Boolean,
      default: true
    },
    downTemplate: {
      type: Boolean,
      default: true
    },
    showIndex: {
      type: Boolean,
      default: true
    },
    exportBtn: {
      type: Boolean,
      default: true
    },
    batchDelBtn: {
      type: Boolean,
      default: true
    },
    exportPath: String,
    addBtn: {
      type: Boolean,
      default: true
    },
    operationWidth: {
      type: Number,
      default: 220
    },
    tableH: {
      type: Number,
      default: 640
    },
    cutHeight: {
      type: Number,
      default: 280
    },
    columns: Array,
    data: Array,
    searchparam: Object,
    operate: {
      type: Array,
      default: function () {
        return [{
          name: '编辑',
          type: 'info',
          size: 'small',
          method: 'editFn'
        },
          {
            name: '删除',
            type: 'error',
            size: 'small',
            method: 'deleteFn'
          }]
      }
    }
  },
  data() {
    return {
      header: {Authorization: "Bearer " + Cookies.getJSON('TOKEN')},
      tableHeight: 640,
      searchTxt: '',
      visible: false,
      deleteDisabled: true,
      dataShow: [],
      showNum: 20,
      currentPage: 1,
      modalEdit: false,
      modalAdd: false,
      modalDelete: false,
      dataEdit: {},
      dataDelete: [],
      operateData: [],
      batchDel: false,
      filearray: []
      // dataAdd: {}
    }
  },
  methods: {
    handleBeforeUpload(file, a, v, b) {

      this.filearray.push(file)
      this.$Spin.show({
        render: (h) => {
          return h('div', [
            h('Icon', {
              'class': 'demo-spin-icon-load',
              props: {
                type: 'load-c',
                size: 18
              }
            }),
            h('div', '上传中...')
          ])
        }
      });
    },
    handleSuccess(res) {

      this.$Spin.hide();
      this.$Message.success(res.msg);
      this.$emit('importSuccess', res);
    },
    handleError(error, response) {
      this.$Spin.hide();
      this.$Message.success(res.msg);
    },
    searchFn() {
      this.$emit('searchFn', this.searchTxt);
    },
    restFn() {
      this.searchTxt = '';
      this.$emit('restFn', this.searchTxt);
    },
    dispenseFn: function (method, data) {
      if (method == 'deleteFn') {
        this.modalDelete = true;
      } else {
        this.$emit(method, this.dataEdit);
      }
    },
    addFn: function () {
      this.$emit('addFn')
      // this.$emit('addFn', this.dataAdd)
    },
    templateDownload() {
      window.location.href = this.exportPath;
    },
    exportFn: function () {
      this.$emit('exportFn', this.searchTxt)
    },
    pageChange: function (page) {
      this.$emit('page-change', page)
    },
    selectChange: function (data) {
      this.batchDel = true;
      this.dataDelete = data;
    },
    deleteOk: function () {
      this.$emit('deleteFn', this.dataDelete);
    },
    batchDelect() {
      if (this.batchDel) {
        this.modalDelete = true;
      } else {
        this.$Message.error('选择需要删除的选项!');
      }
    },
    renderOperate: function (h, params) {
      const op = [];
      for (let i in this.operate) {
        op.push(
          h('Button', {
            props: {
              type: this.operate[i].type,
              size: 'small'
            },
            style: {
              marginRight: '5px'
            },
            on: {
              click: () => {
                const dels = {};
                for (let j in params.row) {
                  if (j !== '_index' && j !== '_rowKey') {
                    this.dataEdit[j] = params.row[j];
                    dels[j] = params.row[j];
                  }
                }
                this.dataDelete = []
                this.dataDelete.push(dels);
                this.dispenseFn(this.operate[i].method, this.dataEdit);
                this.modalEdit = true
              }
            }
          }, this.operate[i].name)
        );
      }
      return op;
    },
    convertKey: function (value) {
      let returnValue = value
      this.columns.forEach(function (elem) {
        for (let i in elem) {
          if (i === 'key' && elem[i] === value) {
            returnValue = elem.title
          }
        }
      })
      return returnValue
    }
  },
  computed: {
    showColumns: function () {
      let showColumn = this.columns.slice()
      // showColumn.forEach(function(elem) {
      //   elem.sortable = true
      // })
      if (this.operate.length > 0) {
        showColumn.push({
          title: '操作',
          key: 'action',
          width: this.operationWidth,
          align: 'center',
          render: this.renderOperate
        })
      }
      return showColumn
    }
  },
  watch: {
    filearray: {//深度监听，可监听到对象、数组的变化
      handler(val, oldVal) {
        var that = this;
        var a = 0;
        setTimeout(function (val) {
          if (a==0) {
            a=1
            API.importexcel(that.actionsuccess).then(resp => {
              a=0
              that.$Spin.hide();
              that.$Message.success(resp.msg);
            })

          }
        }, 3000);
      }
    },
    data: function () {
      this.dataShow = this.data.slice(0, this.showNum)
    },
    dataDelete: function () {
      if (this.dataDelete.length === 0) {
        this.deleteDisabled = true
      } else {
        this.deleteDisabled = false
      }
    }
  },
  mounted: function () {

    this.dataShow = this.data.slice(0, this.showNum);
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - this.cutHeight;
  }
}
</script>

<style scoped>
.controlBox {
  height: 40px;
  line-height: 40px;
  text-align: right;
  display: flex;
  justify-content: space-between;
}
</style>
